const CancelToken = axios.CancelToken;
// 默认初始化 建议修改
axios.interceptors.request.use(
  (suc) => {
    if (sessionStorage.getItem("token")) {
      suc.header.token = sessionStorage.getItem("token");
    }
    return suc;
  },
  (err) => {
    return err;
  }
);
axios.interceptors.response.use(
  (suc) => {
    console.log(suc);
    return suc.data;
  },
  (err) => {
    switch (err.response.status) {
      case 400:
        //console.error("错误请求")
        break;
      case 401:
        //console.error("未授权，请重新登录")
        break;
      case 403:
        //console.error("拒绝访问")
        break;
      case 404:
        //console.error("请求错误，未找到该资源")
        break;
      case 408:
        //console.error("请求超时")
        break;
      case 500:
        //console.error("服务器端出错")
        break;
      default:
      //console.error(`连接错误${err.response.status}`)
    }
    return err;
  }
);
const header = {
  //Authorization: "123"
};
const objCallback = function (method, url, data) {
  //console.log(method)
  const obj = {
    url: url,
    data: data,
    timeout: 5000,
    params: {
      ...data,
    },
    method: method,
    headers: {
      ...header,
    },
    cancelToken: new CancelToken(function (res) {
      console.log(res);
      // res('121') 执行就会 取消发送请求
    }),
  };
  if (method === "post") {
    delete obj.params;
  }
  if (method === "get") {
    delete obj.data;
  }
  return axios(obj);
};
const httpAxios = function (method, url, data) {
  const http = objCallback(method, url, data);
  return http;
};
const http = axios.create({
  timeout: 3000,
  baseURL: "http://localhost:3000",
});
http.interceptors.request.use(
  (suc) => {
    if (sessionStorage.getItem("token")) {
      suc.headers.token = sessionStorage.getItem("token");
    }
    return suc;
  },
  (err) => {
    return err;
  }
);
http.interceptors.response.use(
  (suc) => {
    console.log(suc);
    return suc.data;
  },
  (err) => {
    return err;
  }
);
